<?php

namespace App\Utility;

use EasySwoole\Component\Singleton;
use EasySwoole\Component\TableManager;
use Swoole\Table;

/**
 *  流水号管理
 *
 * @Author LYC 17750800820@163.com
 * @DateTime 2020-04-24 00:30:57
 */
class Ccid
{
    use Singleton;
    protected $table;  // 储存上下文信息的Table
    protected $ccid = 0; // 流水号
    
    public function __construct()
    {
        TableManager::getInstance()->add('ccid', [
            'fd' => ['type' => Table::TYPE_INT, 'size' => 8]
        ]);

        $this->table = TableManager::getInstance()->get('ccid');
    }

    /**
     * 获取一个流水号
     *
     * @Author LYC 17750800820@163.com
     * @DateTime 2020-04-22 15:01:38
     * @return int $ccid
     */
    public function get()
    {
        $ccid = ++$this->ccid;
        if ($ccid > 16000) {
            $this->ccid = 0;
        }
        return $ccid;
    }

    /**
     * 记录一个流水号对应的网页客户端
     *
     * @Author LYC 17750800820@163.com
     * @DateTime 2020-04-22 14:51:30
     * @param string $ccid
     * @param string $fd
     * @return void
     */
    public function set($ccid, $fd)
    {
        return $this->table->set($ccid, [
            'fd' => $fd,
        ]);
    }

    /**
     * 获取指定流水的网页客户端
     *
     * @Author LYC 17750800820@163.com
     * @DateTime 2020-04-22 15:01:38
     * @param integer $ccid
     * @return void
     */
    public function getFd($ccid)
    {
        $info = $this->table->get($ccid);
        return is_array($info) ? $info : null;
    }
    
    /**
     * 删除该流水
     *
     * @Author LYC 17750800820@163.com
     * @DateTime 2020-04-22 15:01:38
     * @param integer $ccid 流水号
     * @return void
     */
    public function delete($ccid)
    {
        if ($this->table->exist($ccid)) {
            $this->table->del($ccid);
        }
    }

    /**
     * 直接获取当前的表
     * @return Table|null
     */
    public function table()
    {
        return $this->table;
    }
}
